package chap04.Postfix;


public class Postfix {

    private StackO charStack = null;

    private StackO postfix = null;

    public Postfix(){
        charStack = new StackO(10);
        postfix = new StackO(20);
    }

    public static void main(String[] agrs) {
        String expression = "A+B*(C-D)";
        Postfix infix = new Postfix();
        System.out.println(infix.doParse(expression));
    }

    public String doParse(String expression) {

        char[] cs = expression.toCharArray();
        for (int i=0; i<cs.length; i++) {
            char z = cs[i];
            if (isNumber((int)z)) {
                postfix.push(z);
            } else {
                //遇到符号的时候需要计算，比较优先级

                if (charStack.isEmpty()) {
                    charStack.push(z);
                } else {
                    char c = (char)charStack.peek();
                    if (isFirst(c,z)) {
                        //计算
                        calculate();
                        if (z == ')') {
                            char ce = (char)charStack.peek();
                            while (ce!='(') {
                                calculate();
                                ce = (char)charStack.peek();
                            }
                            charStack.pop();
                        } else {
                            charStack.push(z);
                        }
                    } else {
                        charStack.push(z);
                    }
                }

            }
        }
        // 计算
        int a = 0;
        while (!charStack.isEmpty()){
            calculate();
        }
        char[] postfixexp = new char[postfix.size()];
        for (int i=postfix.size()-1;i>=0;i--) {
            postfixexp[i] = (char)postfix.pop();
        }
        return new String(postfixexp);
    }

    public boolean isNumber(Object o) {
        if(o == null) return false;
        if(o instanceof Number) {
            int a = (int)o;
            if (a>39 && a<48) {
                return false;
            }
            return true;
        }
        if(o instanceof String) {
            String str = (String)o;
            if(str.length() == 0) return false;
            if(str.trim().length() == 0) return false;

            try {
                Double.parseDouble(str);
                return true;
            }catch(NumberFormatException e) {
                return false;
            }
        }
        return false;
    }

    // 比较符号的优先级
    public boolean isFirst(char a, char b) {
        if ((a == '+'|| a=='-') && (b=='*'||b=='/')){
            return false;
        } else if (a == '(' || b == '('){
            return false;
        } else if (b == ')'){
            return true;
        }
        return true;
    }

    public void calculate() {
        char c = (char)charStack.pop();
        postfix.push(c);
    }


}
